#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基本面分析模块
通过东方财富API获取公司基本面信息、财务数据、估值指标等
"""

import requests
import json
from typing import Dict, Optional
import time


class FundamentalAnalyzer:
    """基本面分析器"""
    
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://quote.eastmoney.com/',
            'Accept': 'application/json',
        })
    
    def analyze_stock(self, stock_code: str, stock_name: str) -> Dict:
        """
        对单只股票进行基本面分析
        
        Args:
            stock_code: 股票代码
            stock_name: 股票名称
        
        Returns:
            基本面分析结果
        """
        print(f"  → 基本面分析 {stock_code} {stock_name}...")
        
        # 获取实时行情和基本信息
        basic_info = self._get_basic_info(stock_code)
        
        # 获取财务指标
        financial_info = self._get_financial_indicators(stock_code)
        
        # 获取公司概况
        company_info = self._get_company_profile(stock_code)
        
        # 综合评估
        valuation_assessment = self._assess_valuation(basic_info, financial_info)
        
        result = {
            '股票代码': stock_code,
            '股票名称': stock_name,
            '基本信息': basic_info,
            '财务指标': financial_info,
            '公司概况': company_info,
            '估值评估': valuation_assessment,
        }
        
        print(f"    ✓ 基本面分析完成")
        return result
    
    def _get_basic_info(self, stock_code: str) -> Dict:
        """获取基本信息（实时行情、市值等）"""
        url = "http://push2.eastmoney.com/api/qt/stock/get"
        
        # 判断市场
        if stock_code.startswith('6'):
            secid = f"1.{stock_code}"
        else:
            secid = f"0.{stock_code}"
        
        params = {
            'secid': secid,
            'fields': 'f57,f58,f84,f85,f127,f116,f60,f45,f46,f47,f48,f50,f107,f161,f162,f167,f168,f169,f170'
        }
        
        try:
            response = self.session.get(url, params=params, timeout=15)
            data = response.json()
            
            if data.get('rc') == 0 and data.get('data'):
                info = data['data']
                
                return {
                    '股票代码': stock_code,
                    '最新价': info.get('f60', 0) / 100 if info.get('f60') else 0,  # f60 需要除以100
                    '涨跌幅': info.get('f170', 0) / 100 if info.get('f170') else 0,
                    '市盈率PE': info.get('f162', 0) / 100 if info.get('f162') else 0,
                    '市净率PB': info.get('f167', 0) / 100 if info.get('f167') else 0,
                    '总市值': info.get('f116', 0),  # 单位：元
                    '流通市值': info.get('f117', 0),
                    '行业': info.get('f127', '未知'),
                    '市盈率TTM': info.get('f162', 0) / 100 if info.get('f162') else 0,
                }
            else:
                return self._get_empty_basic_info(stock_code)
                
        except Exception as e:
            print(f"    ⚠ 获取基本信息失败: {e}")
            return self._get_empty_basic_info(stock_code)
    
    def _get_financial_indicators(self, stock_code: str) -> Dict:
        """获取财务指标（ROE、净利润增长率等）"""
        # 东方财富财务指标API
        url = "https://emh5.eastmoney.com/api/CaiWuFenXi/GetMainTargetNew"
        
        params = {
            'code': stock_code,
            'type': '1',  # 1=年报，2=季报
        }
        
        try:
            response = self.session.get(url, params=params, timeout=15)
            data = response.json()
            
            if data.get('Result') and len(data['Result']) > 0:
                latest = data['Result'][0]
                
                return {
                    'ROE': latest.get('ROEJQ', 0),  # 净资产收益率
                    '净利润增长率': latest.get('JLRZZL', 0),
                    '营收增长率': latest.get('YSTZ', 0),
                    '毛利率': latest.get('XSL', 0),
                    '净利率': latest.get('XSJLR', 0),
                    '资产负债率': latest.get('ZCFZL', 0),
                    '报告期': latest.get('REPORT_DATE', ''),
                }
            else:
                return self._get_empty_financial_info()
                
        except Exception as e:
            print(f"    ⚠ 获取财务指标失败: {e}")
            return self._get_empty_financial_info()
    
    def _get_company_profile(self, stock_code: str) -> Dict:
        """获取公司概况"""
        # 东方财富公司概况API
        url = f"https://emweb.eastmoney.com/PC_HSF10/CompanySurvey/PageAjax"
        
        params = {
            'code': f"{'SH' if stock_code.startswith('6') else 'SZ'}{stock_code}"
        }
        
        try:
            response = self.session.get(url, params=params, timeout=15)
            data = response.json()
            
            if data.get('jbzl'):
                jbzl = data['jbzl']
                
                return {
                    '公司名称': jbzl.get('SECNAME', ''),
                    '主营业务': jbzl.get('MAINOP', ''),
                    '所属行业': jbzl.get('BKNAME', ''),
                    '上市日期': jbzl.get('LISTDATE', ''),
                    '注册资本': jbzl.get('ZCZB', ''),
                    '员工人数': jbzl.get('EMPLOYEES', 0),
                }
            else:
                return self._get_empty_company_info()
                
        except Exception as e:
            print(f"    ⚠ 获取公司概况失败: {e}")
            return self._get_empty_company_info()
    
    def _assess_valuation(self, basic_info: Dict, financial_info: Dict) -> Dict:
        """估值评估"""
        pe = basic_info.get('市盈率PE', 0)
        pb = basic_info.get('市净率PB', 0)
        roe = financial_info.get('ROE', 0)
        
        # 估值水平判断
        valuation_level = '合理'
        if pe > 0:
            if pe < 15:
                valuation_level = '低估'
            elif pe > 30:
                valuation_level = '高估'
        
        # PB-ROE匹配度
        pb_roe_match = '一般'
        if roe > 0 and pb > 0:
            # 理想情况：PB应该在ROE的0.8-1.5倍之间
            if pb < roe * 0.8:
                pb_roe_match = '较好（PB相对ROE偏低）'
            elif pb > roe * 1.5:
                pb_roe_match = '偏高（PB相对ROE偏高）'
            else:
                pb_roe_match = '匹配'
        
        # 投资价值判断
        investment_value = '需进一步研究'
        if pe > 0 and pe < 20 and roe > 10:
            investment_value = '具备一定投资价值'
        elif pe > 0 and pe < 15 and roe > 15:
            investment_value = '投资价值较高'
        elif pe > 40 or roe < 5:
            investment_value = '需谨慎'
        
        return {
            '估值水平': valuation_level,
            'PB-ROE匹配度': pb_roe_match,
            '投资价值判断': investment_value,
            '关键指标': {
                'PE': pe,
                'PB': pb,
                'ROE': roe,
            }
        }
    
    def _get_empty_basic_info(self, stock_code: str) -> Dict:
        """返回空的基本信息"""
        return {
            '股票代码': stock_code,
            '最新价': 0,
            '涨跌幅': 0,
            '市盈率PE': 0,
            '市净率PB': 0,
            '总市值': 0,
            '流通市值': 0,
            '行业': '未知',
            '市盈率TTM': 0,
        }
    
    def _get_empty_financial_info(self) -> Dict:
        """返回空的财务信息"""
        return {
            'ROE': 0,
            '净利润增长率': 0,
            '营收增长率': 0,
            '毛利率': 0,
            '净利率': 0,
            '资产负债率': 0,
            '报告期': '',
        }
    
    def _get_empty_company_info(self) -> Dict:
        """返回空的公司信息"""
        return {
            '公司名称': '',
            '主营业务': '',
            '所属行业': '',
            '上市日期': '',
            '注册资本': '',
            '员工人数': 0,
        }
    
    def generate_fundamental_summary(self, result: Dict) -> str:
        """生成基本面分析摘要"""
        basic = result['基本信息']
        financial = result['财务指标']
        valuation = result['估值评估']
        
        summary = f"""
**基本面分析摘要**

**1. 估值水平**
- 市盈率PE: {basic['市盈率PE']:.2f}
- 市净率PB: {basic['市净率PB']:.2f}
- 估值评估: {valuation['估值水平']}

**2. 盈利能力**
- ROE（净资产收益率）: {financial['ROE']:.2f}%
- 净利率: {financial['净利率']:.2f}%
- 毛利率: {financial['毛利率']:.2f}%

**3. 成长性**
- 净利润增长率: {financial['净利润增长率']:.2f}%
- 营收增长率: {financial['营收增长率']:.2f}%

**4. 投资价值判断**
- {valuation['投资价值判断']}
- PB-ROE匹配度: {valuation['PB-ROE匹配度']}
"""
        return summary


def test_single_stock():
    """测试单个股票"""
    analyzer = FundamentalAnalyzer()
    
    result = analyzer.analyze_stock('600519', '贵州茅台')
    
    if result:
        print("\n" + "="*80)
        print(f"股票: {result['股票代码']} {result['股票名称']}")
        print("\n基本信息:")
        for key, value in result['基本信息'].items():
            print(f"  {key}: {value}")
        print("\n财务指标:")
        for key, value in result['财务指标'].items():
            print(f"  {key}: {value}")
        print("\n估值评估:")
        print(f"  {result['估值评估']}")
        
        print("\n" + analyzer.generate_fundamental_summary(result))
        print("="*80)


if __name__ == '__main__':
    test_single_stock()
